<route lang="json5" type="page">
  {
    "needLogin": true,
    "style": {
      "navigationBarTitleText": "设备充值",
    }
  }
</route>

<script lang="ts" setup>
import { computed, ref } from 'vue'
import { onLoad } from '@dcloudio/uni-app'

// 设备信息
const deviceInfo = ref({
  deviceId: '',
  name: '',
  balance: '0.00',
  reading: '0.00',
  type: '' as 'electric' | 'water',
})

// 当前余额
const currentBalance = ref(0)

// 自定义充值金额
const customAmount = ref('')

// 预设充值金额
const presetAmounts = [200, 500, 1000, 2000]

// 选中的充值金额
const selectedAmount = ref<number | null>(presetAmounts[0])

// 支付方式
const paymentMethod = ref('wechat')
const paymentMethods = [
  { value: 'wechat', label: '微信支付', icon: 'home' },
]

// 模拟设备数据映射
const mockDeviceData = {
  // 电表数据
  1111: {
    deviceId: '1111',
    name: '501电表',
    balance: '67.55',
    reading: '660.69',
    type: 'electric' as const,
  },
  1112: {
    deviceId: '1112',
    name: '502电表',
    balance: '10.55',
    reading: '60.69',
    type: 'electric' as const,
  },
  1121: {
    deviceId: '1121',
    name: '503电表',
    balance: '67.55',
    reading: '660.69',
    type: 'electric' as const,
  },
  1122: {
    deviceId: '1122',
    name: '504电表',
    balance: '10.55',
    reading: '60.69',
    type: 'electric' as const,
  },
  1131: {
    deviceId: '1131',
    name: '505电表',
    balance: '89.12',
    reading: '445.32',
    type: 'electric' as const,
  },
  1132: {
    deviceId: '1132',
    name: '506电表',
    balance: '45.67',
    reading: '523.88',
    type: 'electric' as const,
  },
  1141: {
    deviceId: '1141',
    name: '507电表',
    balance: '123.56',
    reading: '712.45',
    type: 'electric' as const,
  },
  1151: {
    deviceId: '1151',
    name: '508电表',
    balance: '56.44',
    reading: '398.77',
    type: 'electric' as const,
  },
  1211: {
    deviceId: '1211',
    name: '601电表',
    balance: '78.99',
    reading: '334.22',
    type: 'electric' as const,
  },
  // 水表数据
  1113: {
    deviceId: '1113',
    name: '501水表',
    balance: '45.00',
    reading: '125.50',
    type: 'water' as const,
  },
  1114: {
    deviceId: '1114',
    name: '502水表',
    balance: '23.80',
    reading: '98.20',
    type: 'water' as const,
  },
  1123: {
    deviceId: '1123',
    name: '503水表',
    balance: '34.20',
    reading: '88.90',
    type: 'water' as const,
  },
  1133: {
    deviceId: '1133',
    name: '505水表',
    balance: '28.90',
    reading: '167.30',
    type: 'water' as const,
  },
  1142: {
    deviceId: '1142',
    name: '507水表',
    balance: '67.20',
    reading: '89.70',
    type: 'water' as const,
  },
  1152: {
    deviceId: '1152',
    name: '508水表',
    balance: '89.30',
    reading: '134.20',
    type: 'water' as const,
  },
  1212: {
    deviceId: '1212',
    name: '601水表',
    balance: '45.60',
    reading: '112.30',
    type: 'water' as const,
  },
}

// 根据设备ID获取设备信息
function getDeviceInfo(deviceId: string) {
  const id = Number.parseInt(deviceId, 10)
  return mockDeviceData[id as keyof typeof mockDeviceData] || null
}

onLoad((options: any) => {
  if (options?.deviceId) {
    const device = getDeviceInfo(options.deviceId)
    if (device) {
      deviceInfo.value = device
      currentBalance.value = Number.parseFloat(device.balance || '0')
    }
  }
})

// 计算最终充值金额
const finalAmount = computed(() => {
  if (customAmount.value) {
    return Number(customAmount.value)
  }
  return selectedAmount.value || 0
})

// 计算充值后余额
const balanceAfterRecharge = computed(() => {
  return currentBalance.value + finalAmount.value
})

// 设备类型相关的文本
const deviceTypeText = computed(() => {
  if (deviceInfo.value.type === 'electric') {
    return {
      title: '电表充值',
      unit: '度',
      reading: '剩余电量',
      name: '电表名称',
    }
  }
  else {
    return {
      title: '水表充值',
      unit: '吨',
      reading: '剩余水量',
      name: '水表名称',
    }
  }
})

// 选择预设金额
function selectPresetAmount(amount: number) {
  selectedAmount.value = amount
  customAmount.value = ''
}

// 输入自定义金额时清除预设选择
function onCustomAmountInput() {
  selectedAmount.value = null
}

// 充值按钮状态
const canRecharge = computed(() => {
  return finalAmount.value > 0
})

// 返回上一页
function goBack() {
  uni.navigateBack()
}

// 提交充值
function submitRecharge() {
  if (!deviceInfo.value.deviceId) {
    uni.showToast({ title: '设备信息异常', icon: 'none' })
    return
  }

  if (!canRecharge.value) {
    uni.showToast({ title: '请选择充值金额', icon: 'none' })
    return
  }

  if (finalAmount.value < 1) {
    uni.showToast({ title: '充值金额不能少于1元', icon: 'none' })
    return
  }

  if (finalAmount.value > 10000) {
    uni.showToast({ title: '单次充值金额不能超过10000元', icon: 'none' })
    return
  }

  // 模拟支付流程
  uni.showModal({
    title: '确认充值',
    content: `设备：${deviceInfo.value.name}\n充值金额：¥${finalAmount.value}\n支付方式：${paymentMethods.find(p => p.value === paymentMethod.value)?.label}\n\n确认要充值吗？`,
    success: (res) => {
      if (res.confirm) {
        uni.showLoading({ title: '支付中...' })

        // 模拟支付请求
        setTimeout(() => {
          uni.hideLoading()
          uni.showToast({ title: '充值成功', icon: 'success' })

          // 延迟返回到充值管理页面
          setTimeout(() => {
            // uni.navigateBack()
            uni.redirectTo({
              url: '/pages-admin/admin/recharge/success',
            })
          }, 500)
        }, 2000)
      }
    },
  })
}
</script>

<template>
  <view class="recharge-page min-h-screen py-3">
    <!-- 设备信息未加载时的提示 -->
    <view v-if="!deviceInfo.deviceId" class="min-h-screen flex flex-col items-center justify-center">
      <text class="mb-4 text-lg text-gray-500">
        设备信息加载中...
      </text>
      <wd-button type="primary" @click="goBack">
        返回
      </wd-button>
    </view>

    <!-- 设备信息已加载时的内容 -->
    <template v-else>
      <!-- 顶部信息 -->
      <wd-card custom-class="mx-3 mt-3 !p-0">
        <view class="p-4">
          <view class="flex items-baseline">
            <text class="text-gray-600">
              {{ deviceTypeText.reading }}：
            </text>
            <text
              class="text-2xl font-bold"
              :class="{ 'text-red-500': parseFloat(deviceInfo.reading) < 0, 'text-green-500': parseFloat(deviceInfo.reading) > 0 }"
            >
              {{ deviceInfo.reading }}
            </text>
            <text class="ml-1 text-sm font-bold">
              {{ deviceTypeText.unit }}
            </text>
          </view>
        </view>
        <view class="flex items-center justify-between border-t border-gray-100 p-3 text-xs text-gray-500">
          <text>{{ deviceTypeText.name }}: {{ deviceInfo.name }}</text>
          <text>表号: {{ deviceInfo.deviceId }}</text>
          <text>余额: {{ deviceInfo.balance }}元</text>
        </view>
      </wd-card>

      <!-- 充值金额选择 -->
      <wd-card custom-class="mx-3 mt-3">
        <view class="py-2">
          <view class="mb-4 text-lg text-black font-medium">
            充值金额
          </view>

          <!-- 预设金额 -->
          <view class="grid grid-cols-2 mb-4 gap-3">
            <view
              v-for="amount in presetAmounts"
              :key="amount"
              class="cursor-pointer border-2 rounded-lg px-4 py-3 text-center transition-all"
              :class="selectedAmount === amount ? 'border-blue-500 bg-blue-100 text-blue-600' : 'border-gray-200 text-gray-700'"
              @click="selectPresetAmount(amount)"
            >
              <view class="text-lg font-medium">
                ¥{{ amount }}
              </view>
            </view>
          </view>

          <!-- 自定义金额输入 -->
          <view class="mb-4">
            <wd-input
              v-model="customAmount"
              type="digit"
              size="large"
              placeholder="输入其他金额"
              prefix-icon="money-circle"
              clearable
              input-mode="decimal"
              @input="onCustomAmountInput"
            >
              <template #prefix>
                <text class="mr-2 text-gray-500">
                  ¥
                </text>
              </template>
            </wd-input>
            <view class="mt-2 text-xs text-gray-400">
              充值金额范围：1-10000元
            </view>
          </view>

          <!-- 充值后余额预览 -->
          <view v-if="finalAmount > 0" class="rounded-lg bg-blue-100 p-3 text-sm">
            <view class="flex items-center justify-between">
              <text class="text-gray-600">
                充值后余额
              </text>
              <text class="text-blue-600 font-medium">
                ¥{{ balanceAfterRecharge.toFixed(2) }}
              </text>
            </view>
          </view>
        </view>
      </wd-card>

      <!-- 充值按钮 -->
      <view class="fixed bottom-0 left-0 right-0 border-t border-gray-200 bg-white p-4 pb-safe">
        <wd-button
          block
          type="primary"
          size="large"
          :disabled="!canRecharge"
          @click="submitRecharge"
        >
          <text v-if="finalAmount > 0">
            确认充值 ¥{{ finalAmount.toFixed(2) }}
          </text>
          <text v-else>
            请选择充值金额
          </text>
        </wd-button>
      </view>

      <!-- 底部安全占位 -->
      <view class="h-20" />
    </template>
  </view>
</template>

    <style scoped>

    </style>
